import com.sun.source.tree.Tree;

import java.time.temporal.Temporal;

public class BinarySearchTree {
    public class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root = null;

    //查找key
    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null){
            if(cur.val > key){
                cur = cur.left;
            }else if(cur.val < key){
                cur = cur.right;
            }else{
                return cur;
            }
        }
        return null;
    }

    //插入元素
    public void insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null){
            if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else{
                return;
            }
        }
        //parent 指向的节点 就是 需要插入的节点位置 的 父亲节点
        if(parent.val > val){
            parent.left = node;
        }else{
            parent.right = node;
        }
    }

    //删除key的值
    public void remove(int key) {
        TreeNode parent = null;
        TreeNode cur = root;
        while (cur != null){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > key){
                parent = cur;
                cur = cur.left;
            }else{
                removeNode(parent,cur);
                return;
            }
        }
    }

    public void removeNode(TreeNode parent,TreeNode cur){
        if(cur.left == null){
            if(cur == root){
                cur.right = root;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                cur.left = root;
            }else if(cur == parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            TreeNode targrtP = cur;
            TreeNode target = cur.right;
            while (target.left != null){
                targrtP = target;
                target = target.left;
            }
            cur.val = target.val;
            if(target == targrtP.left){
                targrtP.left = target.right;
            }else{
                targrtP.right = target.right;
            }
        }
    }

}
